package com.bawei.mq;

import com.alibaba.fastjson.JSONObject;
import com.bawei.pojo.Indent;
import com.bawei.pojo.Order;
import com.bawei.service.IndentService;
import com.bawei.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 消费者：基于插件的延迟消息
 */
@Component
@Slf4j
public class DelayQueueConsumer {

    @Autowired
    private IndentService indentService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    // 监听消息
    @RabbitHandler
    @RabbitListener(queues = "delayed.queue")
    public void receiveDelayQueue(Message message, Channel channel) {


        try {
            String msg = new String(message.getBody());
            //获取到订单的状态
            Indent indent = indentService.getStatus(msg);
            if (indent.getStatus()==0){
                //如果订单过期后状态仍然为0：未支付的状态，则将订单状态修改为2：订单已过期
                System.out.println("义眼丁真，鉴定为:订单已过期");
                //订单过期把商品库存量加回来
                orderService.updateLimitNum2(indent.getMiddleId());
                ValueOperations<String, String> ops = redisTemplate.opsForValue();
                String s = ops.get("goods" + indent.getMiddleId());
                ops.set("goods"+indent.getMiddleId(),Integer.valueOf(s)+1+"");
                indentService.updateStatus(msg);
            }
            log.info("当前时间{}, 收到延迟消息的队列:{},", new Date().toString(), message);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
        } catch (IOException e) {
            e.printStackTrace();
            try {
                System.out.println("签收失败");
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            } catch (IOException ex) {
                ex.printStackTrace();
            }

        }
    }
}
